class DictionaryController < ApplicationController
	# params[:text] を検証し，パラメータが指定されていない場合やテキストの中身が空の場合には解析を行わないようにする
  before_filter :validate_params, :only => :search
  before_filter :analyze_complexity, :only => :search
	require 'MeCab'
	require 'set'
	def search
		input_text = params[:text]
		#input_text = "あらゆる可能性を自分の方へねじ曲げたのだ。"		
		# 検索の対象とするPOSの指定
		pos_list = Set.new ["名詞","副詞","形容詞","動詞"]
		@list = Set.new
		@sentences = Array.new
		@map = Hash.new{|hash,key| hash[key] = Array.new }
		# 形態素解析
		MeCab::Tagger.new("-Ochasen").parse(input_text).split("\n").each_with_index do |line,i|
			if /EOS/ !~ line then
        line.chomp!   
				surface,reading = line.split("\t")[0..1]
				#@map[surface] << i 
				@sentences << {"surface" =>surface,"reading" => reading}
				cur_pos = line.split("\t")[3].split("-")[0]
				if pos_list.include?(cur_pos) == true then
					base_word = line.split("\t")[2]
					@list << base_word
          @map[base_word] << i 
				end
			end 
		end
		# list に含まれる単語の検索
		@dic = Hash.new
		Dictionary.find(:all, :conditions => ["index IN (?)",@list.to_a]).each do |dic|
      if dic.entry.has_key? "reading"
        entry = "#{dic.entry["surface"]}(#{dic.entry["reading"]})"
      else
        entry = dic.entry["surface"]
      end  
      unless dic.sense.nil?# TODO 辞書の登録のやり直し
        senses = dic.sense.map do |sense|
          sense.map { |word|
            "<span title='#{word["reading"]}' >#{word["surface"]}</span>"
          }.join("")
        end
        @dic[dic.id] = {"entry"=> entry,"senses"=>senses}
        @map[dic.index].each do |index|
          if @sentences[index].has_key?("sense_size")
            @sentences[index]["sense_size"] << dic.sense.size
          else
            @sentences[index]["sense_size"] = [dic.sense.size]
          end
        end
      else
        @dic[dic.id] = {"entry"=> entry}
      end
			@map[dic.index].each do |index|
				if @sentences[index].has_key?("dic_keys")
					@sentences[index]["dic_keys"] << dic.id
				else
					@sentences[index]["dic_keys"] = [dic.id]
				end
			end
		end
		# YAMLに変換
	  #	 render :text => {"sentences" => @sentences,"dic" => @dic}.to_yaml
	end
	
	def index

  end

  def inline_defs
		@keyword = [[1,[[6843, "hello"]]],[1,[[6843, "hello"]]],[1,[[6843, "hello"]]]]
		page.replace_html 'result', :partial => 'results'
	end
  
  require 'lib/sentence_complexity/Function'
  def analyze_complexity
    checker = Function.new
    checker.crawl("lib/sentence_complexity/bunkei.seed")
    level = checker.run(params[:text],false)
    matched = checker.matched.join("<br>")
    @text_level = (level == 0) ? "(Sorry, system could't estimate grammar rank of input text." : "(Estimated JLPT Grammar Rank: #{level} #{matched})"
    true
  end
  
  def validate_params
    if params[:text].blank?
      render(:update) {|page| 
        page.replace_html :inline_defs,"<font color='red'>Input Error:: Please input text to above area.</font>" 
      }
      false
    end
  end
end
